package ua.kharkov.knure.pereverziev.diploma.web.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.HibernateUtils;

public class InitialDatabaseFilling {

	private static final Logger log = Logger
			.getLogger(InitialDatabaseFilling.class);

	public static void insertDataMySQL() {

		final Session s = HibernateUtils.getSession();
		HibernateUtils.begin();

		try {
			final InputStream inputStream = InitialDatabaseFilling.class
					.getResourceAsStream("insertData.sql");
			final InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream);
			final BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			final List<String> list = new ArrayList<String>();
			while (bufferedReader.ready()) {
				list.add(bufferedReader.readLine());
			}

			int index = 0;
			for (final String str : list) {
				if (!str.isEmpty() && str.charAt(0) != '#') {
					s.createSQLQuery(str).executeUpdate();
					log.info("\nInserted: " + str);
					index++;
				}
			}
			log.info("Inserted " + index + " records");
		} catch (final IOException e) {
			log.error("Error while inserting data" + e.getMessage());
		}

		HibernateUtils.commit();
		HibernateUtils.close();
	}
}
